import { memo, useState, useEffect, useRef, forwardRef, useImperativeHandle, useMemo } from 'react';
import { Tabs, Popup, List, SearchBar } from 'antd-mobile';
import { useInbizRouter } from '@inbiz/hooks';
import { InbizIcon } from '@inbiz/utils';
import FilterTab from './FilterTab';
import ProcessDraft from './ProcessDraft';
import InfoCard from './ProcessInfo';
import ProcessAssigned from './ProcessAssigned';
import ProcessWillAssign from './ProcessWillAssign';
import ProcessReceive from './ProcessReceive';
import type { TabObject } from './utils';
import { TextWidget, getMessage } from '@inbiz/react';
import './index.less';

const ProcessCenterView = forwardRef(
  (
    props: {
      userInfo: any;
      tabVisible: string | Boolean;
      tabsArray: any[];
      rangeConfig: string;
      processGroup: any;
      customClickItem: any;
    },
    ref,
  ) => {
    const { userInfo, tabVisible, tabsArray, rangeConfig, processGroup, customClickItem } = props;
    const router = useInbizRouter();
    sessionStorage.removeItem('batchApproval');
    let _hash = window.location.hash?.split('?')?.[0]?.split('/');
    const routeParams = _hash[_hash?.length - 1];
    const tabKey = useMemo(() => {
      switch (routeParams) {
        case 'apply':
          return '1';
        case 'todo':
          return '2';
        case 'applying':
          return '3';
        case 'draft':
          return '4';
        case 'toMe':
          return '5';
        case 'myApply':
          return '6';
        case 'done':
          return '7';
        case 'classification':
          return '8';
        case 'assigned':
          return '9';
        case 'willassign':
          return '10';
        case 'receive':
          return '11';
        default:
          return '1';
      }
    }, [routeParams]);

    const [choosedTabKey, setChoosedTabKey] = useState(tabKey);
    const [searchValue, setSearchValue] = useState(localStorage.getItem('inbiz-process-center-searchValue') || '');
    const [visible, setVisible] = useState(false);
    const draftRef = useRef<any>();
    const infoRef = useRef<any>();
    const assignedRef = useRef<any>();
    const willAssignRef = useRef<any>();
    const receiveRef = useRef<any>();
    const filterRef = useRef<any>();

    const initCondition = useMemo(() => {
      return {
        processGroupName: '',
        processCategoryName: getMessage('processCenter.processGroup'),
        processName: getMessage('processCenter.process'),
        processDefId: '',
        date: '',
        status: '',
        statusName: getMessage('processCenter.status'),
        dateName: getMessage('processCenter.date'),
      }
    }, []);

    const initialConditions = () => {
      setSearchValue('');
      localStorage.removeItem('inbiz-process-center-searchValue');
      localStorage.removeItem('inbiz-process-center-filterTab');
      localStorage.removeItem('inbiz-process-center-selectItem');
      filterRef.current?.setCondition(initCondition);
      infoRef.current?.setSelectItem([]);
      sessionStorage.removeItem('batchApproval');
      filterRef.current?.close?.();
    };

    useEffect(() => {
      const processRoute = [
        'apply',
        'log',
        'todo',
        'applying',
        'draft',
        'toMe',
        'myApply',
        'done',
        'classification',
        'assigned',
        'willassign',
        'receive',
        'approval',
        'setassign',
      ];
      router.listen((params: { action: string; location: any }) => {
        if (processRoute?.every((item) => params?.location?.pathname?.indexOf(item) == -1)) {
          initialConditions();
        };
      });
    }, []);

    const _placeholder = useMemo(() => {
      switch (choosedTabKey) {
        case '1':
        case '4':
          return getMessage('Processcenter.placeholder1H5');
        case '2':
        case '5':
        case '7':
        case '8':
          return getMessage('Processcenter.placeholder2H5');
        case '3':
        case '6':
          return getMessage('Processcenter.placeholder3H5');
        default:
          return getMessage('Processcenter.searchProcess');
      }
    }, [choosedTabKey]);

    // 搜索和过滤时获取列表数据
    const getListData = (text: string, condition?: any) => {
      switch (choosedTabKey) {
        case '2':
        case '3':
        case '5':
        case '6':
        case '7':
        case '8':
          infoRef?.current?.getList(text, condition);
          break;
        case '4':
          draftRef?.current?.getList(text, condition);
          break;
        case '9':
          assignedRef?.current?.getList(text, condition);
          break;
        case '10':
          willAssignRef?.current?.getList(text, condition);
          break;
        case '11':
          receiveRef?.current?.getList(text, condition);
          break;
        default:
          break;
      }
    };

    const changeTab = async (key: string) => {
      setChoosedTabKey(key);
      await filterRef.current?.searchApplyList(key);
      getListData('');
    };

    const clickItem = async (item: TabObject) => {
      if (choosedTabKey == item.id) {
        setVisible(false);
        return;
      } else {
        setChoosedTabKey(item?.id);
        const href = window.location.href;
        const equalIndex = href.indexOf('tabKey');
        let _hash = window.location.hash;
        let _hashArray = _hash?.split('/');
        let _type = _hashArray?.[_hashArray?.length - 1]?.split('?')?.[0];
        let _typeIndex = href?.indexOf(_type);
        let newHref = href.slice(0, equalIndex + 7) + item.id;
        let _newHref = newHref;
        let __newHref = newHref;
        newHref =
          _newHref.slice(0, _typeIndex) +
          item.page +
          __newHref.slice(href.indexOf('?', _typeIndex));
        window.history.replaceState({}, '', `${newHref}`);
        setVisible(false);
      }
    };

    const getInitData = async (tabKey: string) => {
      setChoosedTabKey(tabKey);
      await filterRef.current?.searchApplyList(tabKey);
    }

    useEffect(() => {
      getInitData(tabKey)
    }, [tabKey, rangeConfig]);

    const onTabsChange = (key: string) => {
      if (choosedTabKey == key) {
        return;
      } else {
        sessionStorage.removeItem('batchApproval');
        filterRef.current?.close?.();
        setSearchValue('');
        localStorage.removeItem('inbiz-process-center-filterTab');
        localStorage.removeItem('inbiz-process-center-selectItem');
        localStorage.removeItem('inbiz-process-center-searchValue');
        filterRef.current?.setCondition(initCondition);
      }
    };

    useImperativeHandle(ref, () => ({
      changeTab,
      initialConditions,
      getInitData,
    }));

    const childProps = {
      userInfo,
      choosedTabKey,
      condition: filterRef?.current?.condition,
      rangeConfig,
      processGroup,
      searchValue,
      customClickItem,
    };

    const filterProps = {
      getListData,
      searchValue,
      choosedTabKey,
      userInfo,
      rangeConfig,
      processGroup,
      initCondition,
    };

    const getComponent = useMemo(() => {
      let component = null;
      switch (choosedTabKey) {
        case '4':
          component = (
            <ProcessDraft {...childProps} ref={draftRef} />
          );
          break;
        case '2':
        case '3':
        case '5':
        case '6':
        case '7':
        case '8':
          component = <InfoCard {...childProps} ref={infoRef} />;
          break;
        case '9':
          component = <ProcessAssigned {...childProps} ref={assignedRef} />;
          break;
        case '10':
          component = <ProcessWillAssign {...childProps} ref={willAssignRef} />
          break;
        case '11':
          component = <ProcessReceive {...childProps} ref={receiveRef} />
          break;
        default:
          component = <InfoCard {...childProps} ref={infoRef} />
          break;
      }
      return component;
    }, [choosedTabKey, childProps]);

    const isShowTabHeader = (tabVisible == 'visible' || tabVisible === true);
    const ifShowCondition = choosedTabKey != '9' && choosedTabKey != '10' && choosedTabKey != '11';
    return (
      <div className={'homeContainer'}>
        <div style={{ background: '#fff' }}>
          {isShowTabHeader && (
            <div className={'top'}>
              <div className={'topTabs'}>
                <Tabs
                  activeKey={choosedTabKey}
                  onChange={onTabsChange}
                >
                  {tabsArray
                    .filter((ele) => ele.id != 1).map((item: TabObject) => {
                      return (
                        <Tabs.Tab
                          title={
                            <span onClick={() => clickItem(item)}>
                              <TextWidget>{item.title}</TextWidget>
                            </span>
                          }
                          key={item.id}
                        />
                      );
                    })}
                </Tabs>
              </div>
              <div className={'rightList'}>
                <InbizIcon
                  type="icon-ic-liebiao"
                  style={{ fontSize: 20, marginTop: '50%' }}
                  onClick={() => {
                    setVisible(true);
                    filterRef.current?.close?.();
                  }}
                />
              </div>
            </div>
          )}
          {ifShowCondition && (
            <>
              <SearchBar
                clearable
                value={searchValue}
                onChange={setSearchValue}
                onSearch={(value) => {
                  localStorage.setItem('inbiz-process-center-searchValue', value);
                  localStorage.removeItem('inbiz-process-center-filterTab');
                  localStorage.removeItem('inbiz-process-center-selectItem');
                  filterRef.current?.setCondition(initCondition);
                  getListData(value);
                }}
                onClear={() => {
                  localStorage.removeItem('inbiz-process-center-searchValue');
                  localStorage.removeItem('inbiz-process-center-filterTab');
                  localStorage.removeItem('inbiz-process-center-selectItem');
                  filterRef.current?.setCondition(initCondition);
                  getListData('');
                }}
                placeholder={_placeholder}
              />
              <FilterTab {...filterProps} popup={filterRef} />
            </>
          )}
        </div>
        {getComponent}
        <Popup
          position="right"
          visible={visible}
          bodyStyle={{ minWidth: '60vw' }}
          onMaskClick={() => setVisible(false)}
          bodyClassName={'tabPopup'}
        >
          <List>
            {tabsArray
              .filter((ele) => ele.id != '1')
              .map((item) => {
                return (
                  <List.Item key={item.id}>
                    <div
                      className={
                        tabKey == item.id
                          ? 'tabs-popup-item tabs-popup-item-active'
                          : 'tabs-popup-item'
                      }
                      onClick={() => clickItem(item)}
                    >
                      <TextWidget>{item.title}</TextWidget>
                    </div>
                  </List.Item>
                );
              })}
          </List>
        </Popup>
      </div>
    );
  },
);

export default memo(ProcessCenterView);
